package com.cms.web;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.cms.bean.AttachmentBean;
import com.cms.bean.ProductBean;
import com.cms.bean.ProductPicBean;
import com.cms.biz.products.ProductHelper;
import com.cms.biz.rsf.AttachmentHelper;
import com.cms.database.DBHelper;
import com.cms.facade.SessionFacade;
import com.cms.util.FileHelper;
import com.cms.util.SequenceHelper;
import com.cms.util.StringHelper;

public class uploadFilesServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	    response.setHeader("Cache-Control", "no-cache");
	    HttpSession session = request.getSession();
		PrintWriter out = response.getWriter();
		String user = SessionFacade.getUser(session);
		String uploadtype = request.getParameter("uploadtype");
		int infoId = Integer.parseInt(StringHelper.isEmpty(request.getParameter("infoId"), "0"));
		String fileName = "";
		Connection conn = null;
		try {
			conn = DBHelper.getConn();
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(20 * 1024 * 1024);
			factory.setRepository(new File(FileHelper.FILE_TEMP_PATH));
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			List<FileItem> items = upload.parseRequest(request);
			if (items!=null&&items.size()>0) {
				Iterator<FileItem> itr = items.iterator();
				while (itr.hasNext()) {
					FileItem item = (FileItem) itr.next();
					if (item.isFormField()) {
						String filedName = item.getFieldName();
						if(filedName.equals("uploadtype")){
							uploadtype = item.getString();
						}else if(filedName.equals("infoId")){
							infoId = Integer.parseInt(item.getString());
						}
					} else {
						fileName = item.getName();
						String savedPath = "";
						if (uploadtype.equals("1")) {
							savedPath = FileHelper.getNewImgFilePath(infoId,fileName);
						}else if(uploadtype.equals("2")){
							String ext = fileName.substring(fileName.indexOf("."));
							SimpleDateFormat Formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
							fileName = Formatter.format(new Date())+ext;
							savedPath = FileHelper.getCkeditorImgPath(fileName);
						}else if(uploadtype.equals("3")){
							int new_attach_id = SequenceHelper.getSeqNextVal(conn, SequenceHelper.RSF_ATTACHMENT_SEQ);
							savedPath = FileHelper.getRSFAttachmentPath(infoId, new_attach_id, fileName);
							AttachmentBean attachBean = new AttachmentBean();
							attachBean.setId(new_attach_id);
							attachBean.setParentId(infoId);
							attachBean.setFileName(fileName);
							attachBean.setSuffix(fileName.substring(fileName.indexOf('.')));
							attachBean.setCreateUser(user);
							AttachmentHelper.addAttachment(conn, attachBean);
						}else if(uploadtype.equals("4")){
							savedPath = FileHelper.getProductCoverPath(infoId,fileName);
						}else if(uploadtype.equals("5")){
							int new_picture_id = SequenceHelper.getSeqNextVal(conn, SequenceHelper.PRODUCTS_PICTURES_SEQ);
							savedPath = FileHelper.getProductPicturesPath(infoId, new_picture_id, fileName);
							ProductPicBean ppbBean = new ProductPicBean();
							ppbBean.setId(new_picture_id);
							ppbBean.setParentId(infoId);
							ppbBean.setFileName(fileName);
							ppbBean.setSuffix(fileName.substring(fileName.indexOf('.')));
							ppbBean.setCreateUser(user);
							ProductHelper.AddProductPicture(conn, ppbBean);
						}
						File savedFile = new File(savedPath);
						item.write(savedFile);
					}
				}
				
				if(uploadtype.equals("2")){
					String callback = request.getParameter("CKEditorFuncNum");  
			        out.println("<script type=\"text/javascript\">");  
			        out.println("window.parent.CKEDITOR.tools.callFunction(" + callback  
			                + ",'" + FileHelper.getCkeditorImgURL(fileName) + "',''" + ")");  
			        out.println("</script>");  
			        out.flush();  			        			        
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (Exception e2) {
			}
			DBHelper.closeConn(conn);
		}
	}

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}
}
